package netty_5_demo;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;


/**netty服务端
 * */
public class NettyServer {

    public static void main(String[] args) {

        try{
            //配置服务端的线程组
            EventLoopGroup acceptGroup = new NioEventLoopGroup();
            EventLoopGroup sendGroup = new NioEventLoopGroup();
            try{
                ServerBootstrap serverBootstrap = new ServerBootstrap();
//                b.group(bossGroup, workerGroup);//绑定两个线程池
//                b.channel(NioServerSocketChannel.class);//指定NIO的模式，如果是客户端就是NioSocketChannel
//                b.option(ChannelOption.SO_BACKLOG, 1024);//TCP的缓冲区设置
//                b.option(ChannelOption.SO_SNDBUF, 32*1024);//设置发送缓冲的大小
//                b.option(ChannelOption.SO_RCVBUF, 32*1024);//设置接收缓冲区大小
//                b.option(ChannelOption.SO_KEEPALIVE, true);//保持连续
                serverBootstrap.group(acceptGroup,sendGroup).channel(NioServerSocketChannel.class)
                        .option(ChannelOption.SO_BACKLOG, 1024)
                        .option(ChannelOption.SO_SNDBUF, 32*1024)
                        .option(ChannelOption.SO_RCVBUF, 32*1024)
                        .option(ChannelOption.SO_KEEPALIVE, true)
                        .handler(new LoggingHandler(LogLevel.INFO))
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {
                                socketChannel.pipeline().addLast(MarshallingCodeFactory.buildMarshallingDecoder());
                                socketChannel.pipeline().addLast(MarshallingCodeFactory.buildMarshallingEncoder());
                                socketChannel.pipeline().addLast(new SubReqServerHandler());
                            }
                        });
                //绑定端口，同步等待成功
                ChannelFuture f = serverBootstrap.bind(8086).sync();
                //等待服务器监听端口关闭
                f.channel().closeFuture().sync();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //退出
                acceptGroup.shutdownGracefully();
                sendGroup.shutdownGracefully();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
